package globalVisionEntertainment.nba;

import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.ResultSet;
import java.text.SimpleDateFormat;
import java.util.HashMap;

public class PlayerPairScoreGain
{
	private static SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");

	final PartyPlayerScoreGain homeGain;
	final PartyPlayerScoreGain visitorGain;

	double totalGain;

	public PlayerPairScoreGain(String homePlayer, String visitorPlayer)
	{
		homeGain = new PartyPlayerScoreGain(homePlayer);
		visitorGain = new PartyPlayerScoreGain(visitorPlayer);
	}

	/**
	 * 
	 * @param beforeDate
	 * @return 返回false如果没有这两个球员的配对记录。
	 */
	boolean findScoreGain(Connection connection, String beforeDate) throws UnsupportedOperationException
	{
		if (homeGain.proportionalOnCourtMinutes == 0 || visitorGain.proportionalOnCourtMinutes == 0)
			throw new UnsupportedOperationException("proportionalOnCourtMinutes cannot be 0.");

		HashMap<String, Integer> onCourtMap = new HashMap<>();
		HashMap<String, Integer> scoreMap = new HashMap<>();

		onCourtMap.put(homeGain.playerName, 0);
		onCourtMap.put(visitorGain.playerName, 0);
		scoreMap.put(homeGain.playerName, 0);
		scoreMap.put(visitorGain.playerName, 0);

		try
		{

			CallableStatement statement = connection.prepareCall("{CALL `nba`.`getPlayerPairStats`(?, ?, ?)}");
			statement.setString(1, homeGain.playerName);
			statement.setString(2, visitorGain.playerName);
			statement.setString(3, beforeDate);
			ResultSet resultSet = statement.executeQuery();
			if (resultSet.first() == false)
				return false;

			int rows = 0;
			do
			{
				String playerName = resultSet.getString("PlayerName");
				onCourtMap.put(playerName, onCourtMap.get(playerName) + resultSet.getInt("Total on Court"));
				scoreMap.put(playerName, scoreMap.get(playerName) + resultSet.getInt("Total Plus") + resultSet.getInt("Total Minus"));

				rows++;
			} while (resultSet.next() && rows < 10);

			if (System.getProperty("debug", "false").equals("true"))
				System.out.printf("%1s配%2s，有%3d项记录。\n", homeGain.playerName, visitorGain.playerName, rows / 2);

			homeGain.scoreGain = scoreMap.get(homeGain.playerName) * 60.0 / onCourtMap.get(homeGain.playerName);
			visitorGain.scoreGain = scoreMap.get(visitorGain.playerName) * 60.0 / onCourtMap.get(visitorGain.playerName);

			totalGain = homeGain.proportionalOnCourtMinutes * homeGain.scoreGain + visitorGain.proportionalOnCourtMinutes * visitorGain.scoreGain;
			return true;
		}
		catch (Exception e)
		{
			throw new RuntimeException(e);
		}
	}
}
